require_relative 'func'

class Slot
  
  attr_reader :vitality, :field, :index
  attr_writer :vitality, :field
  
  def initialize index
    @vitality = 10000
    @field = I.new
    @index = index
  end
  
  def left_apply x
    $application_num = 0
    begin
      @field = @field.apply x.new
    rescue => e
      @field = I.new
      raise e
    end
    @field
  end
  
  def right_apply x
    $application_num = 0
    begin
      @field = x.new.apply @field
    rescue => e
      @field = I.new
      raise e
    end
  end
  
  def to_s
    "{#{@index},#{@vitality},#{@field.to_s}}"
  end
  
  def dead?
	  vitality <= 0
  end
end

def get_card_by_name n
  case n
    when "I"
      I
    when "zero"
      Zero
    when "succ"
      Succ
    when "dbl"
      Dbl
    when "get"
      Get
    when "put"
      Put
    when "S"
      S
    when "K"
      K
    when "inc"
      Inc
    when "dec"
      Dec
    when "attack"
      Attack
    when "help"
      Help
    when "copy"
      Copy
    when "revive"
      Revive
    when "zombie"
      Zombie
  end
end

def do_application(lr, slot, card)
  begin
    case lr
      when 1
        $my_slots[slot].left_apply(get_card_by_name card)
      when 2
        $my_slots[slot].right_apply(get_card_by_name card)
    end
  rescue =>e
    #... just do nothing, we don't want bad application to break demon
    #raise e
  end
end

def auto_apply
  $auto_application = true
  $my_slots.each do |slot|
    if slot.vitality
      begin
        slot.right_apply(I)
        slot.vitality = 0
      rescue => e
        @field = I.new
        raise e
      end
    end
  end
  $auto_application = false
end